#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include "readSpectrumFile.h"
#include "bandprocessing.h"
#define MAX_NUMBER_OF_BANDS 50

// Example usage: ./bandanalysis <filename> [OPTIONS] 1.5 2.0

int main(int argc, char *argv[])
{	
	char *inputfile;
	inputfile = argv[1];
	printf("\nInput Spectrum File: %s\n",inputfile);
	
	// Variable declaration 
	int numOfChannels, numOfBands = 0, usingranges = 0;
	double lowerb1[MAX_NUMBER_OF_BANDS], upperb1[MAX_NUMBER_OF_BANDS];
	double lowerb2[MAX_NUMBER_OF_BANDS], upperb2[MAX_NUMBER_OF_BANDS];
	
	// Process Command Line arguments.
	int i = 2;
	
	// Default
	if(strcmp(argv[i], "--continuum-points") == 0 || strcmp(argv[i], "-cp") == 0)
	{
			usingranges = 0;
			i++;
	}
	if(strcmp(argv[i], "--continuum-ranges") == 0 || strcmp(argv[i], "-cr") == 0)
	{
			usingranges = 1;
			i++;
	}
	
	if(usingranges == 1)
		printf("Using ranges to define continuum.\n\n");
	else
		printf("Using points to define continuum.\n\n");
	
	// Read in continuum points or ranges
	while(i < argc - 1)
	{
		if(usingranges == 0)
		{
			if( atof(argv[i]) != 0 && atof(argv[i+1]) != 0)
			{
				lowerb1[numOfBands] = atof(argv[i]);
				upperb1[numOfBands] = atof(argv[i+1]);
				numOfBands++;
				i+=2;
			}
			else
			{
				// This shouldn't happen. 
				printf("Bad command line arguments!\n ");
				return -1;
			}
		}
		else
		{
			if(atof(argv[i]) != 0 && atof(argv[i+1]) != 0 && atof(argv[i+2]) != 0 && atof(argv[i+3]) != 0)
			{
				lowerb1[numOfBands] = atof(argv[i]);
				upperb1[numOfBands] = atof(argv[i+1]);
				lowerb2[numOfBands] = atof(argv[i+2]);
				upperb2[numOfBands] = atof(argv[i+3]);
				numOfBands++;
				i+=4;
			}
			else
			{
				// This shouldn't happen. 
				printf("Bad command line arguments!\n ");
				return -1;
			}
		}
	}
	
	// Read file into arrays for wavelengths, data, and errors
	numOfChannels = countChannels(inputfile);
	
	// Converts the input data to double values for computational accuracy. 
	double w[numOfChannels],d[numOfChannels],e[numOfChannels];
	readFile(inputfile,w,d,e,numOfChannels);
	
	// call calcAndDisplayBandParameters function from bandprocessing.h
	// This calculates the band parameters for each band and displays the results to the command line. 
	if(usingranges == 0)
	{
		calcAndDisplayBandParameters(w, d, lowerb1, upperb1, numOfChannels, numOfBands);
	}
	else
	{
		calcAndDisplayBandParameters2(w, d, lowerb1, upperb1, lowerb2, upperb2, numOfChannels, numOfBands);
	}
	return 0;
}
